<?php

namespace App\Console\Commands;

use App\Http\Model\Api\AccompanyUser;
use App\Http\Model\Config;
use App\Lib\ConsumerTopupRebate;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class OrderKing extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'order:king';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '谁是接单王';

    protected $model;
    protected $configModel;

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(AccompanyUser $accompanyUser, Config $config)
    {
        $this->model = $accompanyUser;
        $this->configModel = $config;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->provideDiamond();
    }

    public function effectiveTime() {
        $configs = $this->configModel->getShareGoodsConfig(16);
        $times = $configs['order_king']['value'];

        return explode(' - ', $times);
    }

    public function provideDiamond() {
        $times = $this->effectiveTime();
        $begin = $times[0];
        $end = $times[1];
        $list = $this->model->provideDiamond($begin, $end);

        foreach ($list as $key => $value) {
            $prize = floor($value->total_price / 100 * 0.1 * 80 * 0.05 * 10);
            $this->sendMsg($value->user_id, $prize);
        }
        $this->info('ok');
    }

    public function sendMsg($user_id, $prize) {
        //发送接口请求
        $recharge = [
            'user_id' => $user_id,
            'diamond_num' => $prize,
            'msg' => '谁是接单王',
        ];
        $diamond_api = json_decode(curl_request(env('KK_API_HOST') . '/finance/diamond/recharge', $recharge), true);
        if ($diamond_api['code'] != 0) {
            //充值失败 销毁队列
            write_log('orderKingConsumer', 'addDiamond', json_encode($diamond_api));
            return false;
        }

        // 发送消息
        $msg_data_one['user_id'] = $user_id;
        $msg_data_one['msg'] = "谁是接单王奖励 钻石* " . $prize;
        $res = json_decode(curl_request(env('KK_API_HOST') . '/msg/text', $msg_data_one), true);
        if ($res['code'] != 0) {
            //充值失败 销毁队列
            write_log('orderKingConsumer', 'sendMsg', json_encode($res));
            return false;
        }
        write_log('orderKingConsumer', '谁是接单王返利', $user_id);
    }
}
